package cn.moukou.tongji.ihealth.predication.controller;

import cn.moukou.tongji.ihealth.core.bean.Resp;
import cn.moukou.tongji.ihealth.predication.config.NettyConfig;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RequestMapping("/ihealth/predication/")
@RestController
public class ApiController {

    @Autowired(required = false)
    OSS client;

    public String ossSuffix = "https://tongji-ihealth.oss-cn-shanghai.aliyuncs.com/";

    @Value("${spring.cloud.alicloud.access-key}")
    String accessId;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    String endpoint;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("ping")
    public String hello() {
        return "pong";
    }


    @PostMapping("/input/push")
    public Resp<String> pushPredicationInput(@RequestParam("uid") String uid, @RequestParam("key") String key) {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("url", "https://" + bucket + "." + endpoint + "/" + key);
        String jsonstr = JSON.toJSONString(map);
        rabbitTemplate.convertAndSend("ihealth.exchange", "ihealth.predication.input", jsonstr);
        return Resp.ok("success");
    }

    @GetMapping("/oss/policy")
    public Map<String , String> ossPolicy() {
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        String dir = "ihealth/temp/"; // 用户上传文件时指定的前缀。

        try {
            long expireTime = 300;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            respMap.put("uuid", UUID.randomUUID().toString());
            return respMap;

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            client.shutdown();
        }
        return null;
    }


}
